// server/api/skills/[id].delete.ts
import { defineEventHandler, getRouterParams, getHeader, getQuery } from 'h3'
import { verifyToken } from '../../utils/auth'

export default defineEventHandler(async (event) => {
  try {
    // Token验证
    const authHeader = getHeader(event, 'authorization')
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      throw createError({
        statusCode: 401,
        statusMessage: '未提供认证令牌'
      })
    }
    
    const token = authHeader.slice(7)
    const decoded = verifyToken(token)
    if (!decoded) {
      throw createError({
        statusCode: 401,
        statusMessage: '令牌无效或已过期'
      })
    }
    
    const { id } = getRouterParams(event)
    const query = getQuery(event)
    const { username } = query
    
    if (!username) {
      throw createError({
        statusCode: 400,
        statusMessage: '需要提供用户名'
      })
    }
    
    // 查询用户
    const user = await prisma.user.findUnique({
      where: { username: username as string }
    })
    
    if (!user) {
      throw createError({
        statusCode: 404,
        statusMessage: '用户不存在'
      })
    }
    
    // 验证技能属于该用户
    const skill = await prisma.skill.findFirst({
      where: {
        id: parseInt(id),
        userId: user.id
      }
    })
    
    if (!skill) {
      throw createError({
        statusCode: 404,
        statusMessage: '技能不存在或无权删除'
      })
    }
    
    // 删除技能
    await prisma.skill.delete({
      where: { id: parseInt(id) }
    })
    
    return {
      code: 200,
      message: '技能删除成功'
    }
    
  } catch (error: any) {
    console.error('删除技能错误:', error)
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || '删除失败'
    })
  }
})